package com.game.core.frame
{
	import com.game.core.GlobalInterface;
	
	import flash.display.Sprite;
	
	public class UpdatableSprite extends Sprite implements IFrameUpdatable
	{
		private var _frameRate  : int = 0;
		private var _frameElapsedTime : int = 0; 
		private var _frameTimes : int = 0;
		private var _elapsedTimes : int = 0;
		private var _isRegistered : Boolean = false;
		protected var _needCheckUpdatable : Boolean = false;	
		
		public function UpdatableSprite()
		{
			super();
		}
		
		public function get isRegister():Boolean
		{
			return _isRegistered;
		}
		
		public function notifyRegisterd():void
		{
			_isRegistered = true;
		}
		
		public function notifyUnRegisterd():void
		{
			_isRegistered = false;
		}
		
		public function update(elapsedTime:int):void
		{
		}
		
		public function checkUpdatable(elapsedTime:int):Boolean
		{
			if(!_needCheckUpdatable)
			{
				_elapsedTimes = elapsedTime;
				return true;
			}
			
			if(_frameElapsedTime == 0)
				_elapsedTimes = 0;
			
			_frameElapsedTime += elapsedTime;
			_elapsedTimes += elapsedTime;
			
			if(_frameElapsedTime > _frameTimes)
			{
				_frameElapsedTime = 0;
				return true;
			}
			return false;
		}

		public function set frameRate(value:int):void
		{
			if(value < 1 || _frameRate > GlobalInterface.frameRate)
			{
				_frameRate = GlobalInterface.frameRate;
				return;
			}
			
			_frameRate = value;
			
			if(_frameRate != GlobalInterface.frameRate)
			{
				_frameTimes = 1000 / _frameRate;
				_needCheckUpdatable = true;
			}else
			{
				_needCheckUpdatable = false;
			}
		}
		
		public function get frameTimes():int
		{
			return _frameTimes;
		}
		
		public function set frameTimes(value:int):void
		{
			value = Math.max(0,value);
			_frameTimes = value;
			if(value == 0)
			{
				_needCheckUpdatable = false;
			}else
			{
				_needCheckUpdatable = true;
			}
		}
		
		public function register(priority : int = 0):void
		{
			if(_isRegistered)return;
			FrameManager.getInstance().register(this ,priority);
		}
		
		public function unRegister():void
		{
			if(!_isRegistered)return;
			FrameManager.getInstance().unRegister(this);
		}

		public function get elapsedTimes():int
		{
			return _elapsedTimes;
		}


	}
}